#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/kdev_t.h>
#include <linux/cdev.h>

#include <linux/uaccess.h>


static dev_t dev_num;
static int major;
static int minor;
struct cdev cdev_test;

struct class *class;
struct device *device;


static int cdev_open(struct inode *inode, struct file *file)
{
    printk(KERN_EMERG "This is cdev_open\r\n");
    return 0;
}

static ssize_t cdev_write(struct file *file, const char __user *buff, size_t size, loff_t * off)
{
    char kbuf[32] = {0};
    if (copy_from_user(kbuf, buff, size) != 0)
    {
        printk(KERN_EMERG "copy_from_user error\r\n");
        return -1;
    }
    printk(KERN_EMERG "This is cdev_write\r\n");
    printk(KERN_EMERG "kbuf : %s\r\n", kbuf);

    return 0;
}


static ssize_t cdev_read(struct file *file, char __user *buff, size_t size, loff_t *off)
{
    char kbuf[32] = "This is cdev_test_read!";
    if (copy_to_user(buff, kbuf, size) != 0)
    {
        printk(KERN_EMERG "copy_to_user error\r\n");
        return -1;
    }
    printk(KERN_EMERG "This is cdev_read\r\n");
    return 0;
}


static int cdev_release (struct inode *inode, struct file *file)
{
    printk(KERN_EMERG "This is cdev_release\r\n");
    return 0;
}


struct file_operations cdev_fops = {
    .owner = THIS_MODULE,
    .open = cdev_open,
    .read = cdev_read,
    .write = cdev_write,
    .release = cdev_release,
};


static int __init chrdev_init(void)
{
    int ret ;

    ret = alloc_chrdev_region(&dev_num, 0, 1, "chrdev_test");
    if (ret < 0)
    {
        printk(KERN_EMERG "alloc chrdev is error\n");
        return -1;
    }
    printk(KERN_EMERG "alloc chrdev is ok\n");

    major = MAJOR(dev_num);
    minor = MINOR(dev_num);
    printk(KERN_EMERG "major = %d  | minor = %d\n", major, minor);

    cdev_test.owner = THIS_MODULE;
    cdev_init(&cdev_test, &cdev_fops);
    cdev_add(&cdev_test, dev_num, 1);

    class = class_create(THIS_MODULE, "test");
    device = device_create(class, NULL, dev_num, NULL, "chr_test");

    return 0;
}


static void __exit chrdev_exit(void)
{
    device_destroy(class, dev_num);
    class_destroy(class);
    cdev_del(&cdev_test);
    unregister_chrdev_region(dev_num, 1);
}


module_init(chrdev_init);
module_exit(chrdev_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("treasure1029");


